<!-- 分配角色弹出层 -->
<template>
  <el-dialog
    v-model="isShowRolePopup"
    title="分配角色"
    width="500px"
    :before-close="cancel"
  >
    <el-form>
      <el-form-item>
        <el-select
          v-model="optionForm.selectRole"
          placeholder="请选择"
          multiple
          style="width: 260px"
        >
          <el-option
            v-for="item in form"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="open">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, Ref, watch } from 'vue';
import {
  GetRoleAllApi,
  updateRoleApi,
  GetAppointRoleApi,
} from '../../../request/api';
import { ElMessage, ElMessageBox } from 'element-plus';
// 初始请求函数
function fetchData() {
  GetRoleAllApi().then((res) => {
    if (res.code == 200) {
      form.value = res.data;
    }
  });
}
fetchData();
// 弹出框数据
const form = ref([]) as Ref<GetRoleAllData[]>;
// 下拉选项默认值
let optionForm = ref({
  selectRole: [] as number[],
});

// 子组件接收父组件传过来的数据
let props = defineProps<{
  isShowRolePopup: boolean;
  roleId: number;
}>();

let emit = defineEmits<{
  (event: 'rolehidden'): void;
}>();
function cancel() {
  emit('rolehidden');
}
// 监听
watch(
  () => props.roleId,
  (newVal, oldVal) => {
    if (newVal) {
      GetAppointRoleApi(newVal).then((res) => {
        if (res.code == 200) {
          optionForm.value.selectRole = res.data.map((item) => item.id);
        }
      });
    }
  }
);
// 点击确定事件
const open = () => {
  ElMessageBox.confirm('此操作将修改当前用户角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      updateRoleApi({
        adminId: props.roleId,
        roleIds: optionForm.value.selectRole.join(','),
      }).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '操作成功',
          });
          cancel();
        }
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // });
    });
};
</script>
<style lang="less" scoped>
:deep(.el-button) {
  width: 80px;
  height: 40px;
}
:deep(.el-tag) {
  --el-tag-font-size: 14px;
}
</style>
